package com.gframework.antibrush.limiter;

import org.redisson.Redisson;
import org.redisson.api.RRateLimiter;
import org.redisson.api.RateIntervalUnit;
import org.redisson.api.RateType;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnSingleCandidate;

/**
 * 基于redisson redis客户端的限流实现.
 * 
 * @since 1.0.0
 * @author Ghwolf
 */
@ConditionalOnClass({Redisson.class,RedissonClient.class})
@ConditionalOnSingleCandidate(RedissonClient.class)
@ConditionalOnMissingBean(CurrentLimiter.class)
public class CurrentLimiterRedisson implements CurrentLimiter{
	
	@Autowired
	private RedissonClient redisson ;
	
	@Override
	public boolean rate(LimitRequest anno, String key) {
		RRateLimiter r = redisson.getRateLimiter(key);
		if (!r.isExists()) {
			r.trySetRate(RateType.OVERALL, anno.maxRequest(), anno.timeUnit().toMillis(anno.time()),
					RateIntervalUnit.MILLISECONDS);
		}
		return r.tryAcquire();
	}

}
